<template>
  <view class="page">
    <!-- 购物车列表 -->
    <scroll-view class="cart-list" scroll-y v-if="cartList.length > 0">
      <view class="cart-item" v-for="(item, index) in cartList" :key="item.productId">
        <view class="item-checkbox" @click="toggleSelect(index)">
          <text class="checkbox" :class="{ checked: item.selected }">
            {{ item.selected ? '✓' : '' }}
          </text>
        </view>
        
        <image 
          class="item-image" 
          :src="item.image || '/static/images/product-default.png'"
          mode="aspectFill"
        ></image>
        
        <view class="item-info">
          <text class="item-name">{{ item.name }}</text>
          <view class="item-footer">
            <view class="item-price">
              <text class="price-symbol">¥</text>
              <text class="price-value">{{ item.price }}</text>
            </view>
            
            <view class="item-quantity">
              <view 
                class="btn-minus" 
                :class="{ disabled: item.quantity <= 1 }"
                @click="decreaseQuantity(index)"
              >-</view>
              <text class="quantity-text">{{ item.quantity }}</text>
              <view 
                class="btn-plus" 
                :class="{ disabled: item.quantity >= item.stock }"
                @click="increaseQuantity(index)"
              >+</view>
            </view>
          </view>
        </view>
        
        <view class="item-delete" @click="deleteItem(index)">
          <text class="delete-icon">🗑️</text>
        </view>
      </view>
    </scroll-view>
    
    <!-- 空状态 -->
    <view class="empty" v-else>
      <text class="empty-icon">🛒</text>
      <text class="empty-text">购物车空空如也</text>
      <view class="empty-btn" @click="goToShop">
        <text>去逛逛</text>
      </view>
    </view>
    
    <!-- 底部结算栏 -->
    <view class="bottom-bar" v-if="cartList.length > 0">
      <view class="bar-content">
        <view class="bar-top" v-if="minOrderAmount > 0 && selectedCount > 0">
          <view class="min-tip" :class="{ reached: isMinAmountReached }">
            <text class="tip-icon">{{ isMinAmountReached ? '✅' : '⚠️' }}</text>
            <text class="tip-text" v-if="isMinAmountReached">已满足起送金额</text>
            <text class="tip-text" v-else>还差 ¥{{ remainingAmount }} 起送</text>
          </view>
        </view>
        
        <view class="bar-bottom">
          <view class="bar-left">
            <view class="checkbox-all" @click="toggleSelectAll">
              <text class="checkbox" :class="{ checked: isAllSelected }">
                {{ isAllSelected ? '✓' : '' }}
              </text>
              <text class="checkbox-label">全选</text>
            </view>
            
            <view class="total-info">
              <text class="total-label">合计：</text>
              <text class="total-symbol">¥</text>
              <text class="total-value">{{ totalPrice }}</text>
            </view>
          </view>
          
          <view class="bar-right">
            <view 
              class="btn-checkout" 
              :class="{ disabled: selectedCount === 0 || !isMinAmountReached }"
              @click="checkout"
            >
              <text class="btn-text" v-if="selectedCount === 0">请选择商品</text>
              <text class="btn-text" v-else-if="!isMinAmountReached">还差¥{{ remainingAmount }}</text>
              <text class="btn-text" v-else>结算({{ selectedCount }})</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      cartList: [],
      minOrderAmount: 0 // 起送金额
    }
  },
  computed: {
    // 是否全选
    isAllSelected() {
      return this.cartList.length > 0 && this.cartList.every(item => item.selected)
    },
    
    // 已选商品数量
    selectedCount() {
      return this.cartList.filter(item => item.selected).reduce((sum, item) => sum + item.quantity, 0)
    },
    
    // 总价
    totalPrice() {
      return this.cartList
        .filter(item => item.selected)
        .reduce((sum, item) => sum + item.price * item.quantity, 0)
        .toFixed(2)
    },
    
    // 是否满足起送金额
    isMinAmountReached() {
      return parseFloat(this.totalPrice) >= parseFloat(this.minOrderAmount)
    },
    
    // 距离起送金额还差多少
    remainingAmount() {
      const remaining = parseFloat(this.minOrderAmount) - parseFloat(this.totalPrice)
      return remaining > 0 ? remaining.toFixed(2) : 0
    }
  },
  onShow() {
    this.loadCart()
    this.loadMinOrderAmount()
  },
  methods: {
    async loadMinOrderAmount() {
      try {
        const { getPublicConfigs } = require('@/api/config')
        const configs = await getPublicConfigs()
        
        if (configs && configs.minOrderAmount) {
          this.minOrderAmount = parseFloat(configs.minOrderAmount) || 0
        }
      } catch (error) {
        console.error('加载起送金额失败:', error)
        this.minOrderAmount = 0
      }
    },
    
    loadCart() {
      const cart = uni.getStorageSync('cart') || []
      this.cartList = cart
    },
    
    saveCart() {
      uni.setStorageSync('cart', this.cartList)
      
      // 更新购物车数量
      const totalCount = this.cartList.reduce((sum, item) => sum + item.quantity, 0)
      uni.setStorageSync('cartCount', totalCount)
    },
    
    toggleSelect(index) {
      this.cartList[index].selected = !this.cartList[index].selected
      this.saveCart()
    },
    
    toggleSelectAll() {
      const newValue = !this.isAllSelected
      this.cartList.forEach(item => {
        item.selected = newValue
      })
      this.saveCart()
    },
    
    increaseQuantity(index) {
      const item = this.cartList[index]
      if (item.quantity < item.stock) {
        item.quantity++
        this.saveCart()
      } else {
        uni.showToast({
          title: '库存不足',
          icon: 'none'
        })
      }
    },
    
    decreaseQuantity(index) {
      const item = this.cartList[index]
      if (item.quantity > 1) {
        item.quantity--
        this.saveCart()
      }
    },
    
    deleteItem(index) {
      uni.showModal({
        title: '提示',
        content: '确定要删除该商品吗？',
        success: (res) => {
          if (res.confirm) {
            this.cartList.splice(index, 1)
            this.saveCart()
            
            uni.showToast({
              title: '已删除',
              icon: 'success'
            })
          }
        }
      })
    },
    
    checkout() {
      if (this.selectedCount === 0) {
        uni.showToast({
          title: '请选择商品',
          icon: 'none'
        })
        return
      }
      
      // 校验起送金额
      if (!this.isMinAmountReached) {
        uni.showToast({
          title: `还差¥${this.remainingAmount}元起送`,
          icon: 'none',
          duration: 2000
        })
        return
      }
      
      // 获取选中的商品
      const selectedItems = this.cartList
        .filter(item => item.selected)
        .map(item => ({
          productId: item.productId,
          name: item.name,
          image: item.image,
          price: item.price,
          quantity: item.quantity
        }))
      
      // 跳转到订单确认页
      uni.navigateTo({
        url: '/pages/order/confirm?from=cart&items=' + encodeURIComponent(JSON.stringify(selectedItems))
      })
    },
    
    goToShop() {
      uni.switchTab({
        url: '/pages/index/index'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.cart-list {
  flex: 1;
  padding: 20rpx;
  padding-bottom: 200rpx;
}

.cart-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  display: flex;
  gap: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.item-checkbox {
  display: flex;
  align-items: center;
  
  .checkbox {
    width: 40rpx;
    height: 40rpx;
    border: 2rpx solid #ddd;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24rpx;
    color: #fff;
    
    &.checked {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border-color: #667eea;
    }
  }
}

.item-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item-name {
  font-size: 28rpx;
  color: #333;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  line-height: 1.4;
}

.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-price {
  display: flex;
  align-items: baseline;
  gap: 4rpx;
  
  .price-symbol {
    font-size: 22rpx;
    color: #ff4d4f;
    font-weight: bold;
  }
  
  .price-value {
    font-size: 32rpx;
    color: #ff4d4f;
    font-weight: bold;
  }
}

.item-quantity {
  display: flex;
  align-items: center;
  gap: 16rpx;
  
  .btn-minus,
  .btn-plus {
    width: 44rpx;
    height: 44rpx;
    border: 2rpx solid #ddd;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    color: #333;
    
    &.disabled {
      opacity: 0.3;
    }
  }
  
  .quantity-text {
    font-size: 28rpx;
    color: #333;
    min-width: 60rpx;
    text-align: center;
  }
}

.item-delete {
  display: flex;
  align-items: center;
  
  .delete-icon {
    font-size: 40rpx;
  }
}

/* 空状态 */
.empty {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  
  .empty-icon {
    font-size: 160rpx;
    margin-bottom: 40rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 60rpx;
  }
  
  .empty-btn {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
    font-size: 28rpx;
    padding: 20rpx 60rpx;
    border-radius: 40rpx;
  }
}

/* 底部结算栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.bar-content {
  display: flex;
  flex-direction: column;
}

.bar-top {
  padding: 16rpx 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.min-tip {
  display: flex;
  align-items: center;
  gap: 12rpx;
  padding: 12rpx 16rpx;
  border-radius: 8rpx;
  background: linear-gradient(135deg, #fff5f5 0%, #ffe0e0 100%);
  
  &.reached {
    background: linear-gradient(135deg, #f0fff4 0%, #c6f6d5 100%);
  }
  
  .tip-icon {
    font-size: 24rpx;
  }
  
  .tip-text {
    font-size: 22rpx;
    color: #666;
  }
}

.bar-bottom {
  padding: 24rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.bar-left {
  display: flex;
  align-items: center;
  gap: 32rpx;
}

.checkbox-all {
  display: flex;
  align-items: center;
  gap: 16rpx;
  
  .checkbox {
    width: 40rpx;
    height: 40rpx;
    border: 2rpx solid #ddd;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24rpx;
    color: #fff;
    
    &.checked {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border-color: #667eea;
    }
  }
  
  .checkbox-label {
    font-size: 26rpx;
    color: #333;
  }
}

.total-info {
  display: flex;
  align-items: baseline;
  gap: 4rpx;
  
  .total-label {
    font-size: 24rpx;
    color: #666;
  }
  
  .total-symbol {
    font-size: 22rpx;
    color: #ff4d4f;
    font-weight: bold;
  }
  
  .total-value {
    font-size: 36rpx;
    color: #ff4d4f;
    font-weight: bold;
  }
}

.btn-checkout {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 24rpx 48rpx;
  border-radius: 40rpx;
  
  &.disabled {
    opacity: 0.5;
  }
  
  .btn-text {
    font-size: 28rpx;
    color: #fff;
    font-weight: bold;
  }
}
</style>
